import React, { useRef, useEffect, useState } from 'react';

export default function CameraModal({ onClose, onCapture }) {
  const videoRef = useRef(null);
  const streamRef = useRef(null);
  const mediaRecorderRef = useRef(null);
  const chunksRef = useRef([]);
  const timerRef = useRef(null);
  const recordTimeoutRef = useRef(null);
  const [isRecording, setIsRecording] = useState(false);

  useEffect(() => {
    let isMounted = true;
    // 强制限制分辨率，优先用exact，失败降级用max 没座
    const getStream = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { width: { exact: 640 }, height: { exact: 480 }, facingMode: 'user' },
          audio: true
        });
        if (!isMounted) { stream.getTracks().forEach(track => track.stop()); return; }
        streamRef.current = stream;
        videoRef.current.srcObject = stream;
        videoRef.current.play();
      } catch (e) {
        // exact不支持时降级max
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { width: { max: 640 }, height: { max: 480 }, facingMode: 'user' },
          audio: true
        });
        if (!isMounted) { stream.getTracks().forEach(track => track.stop()); return; }
        streamRef.current = stream;
        videoRef.current.srcObject = stream;
        videoRef.current.play();
      }
    };
    getStream();
    return () => {
      isMounted = false;
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => track.stop());
        streamRef.current = null;
      }
      if (mediaRecorderRef.current) {
        if (mediaRecorderRef.current.state !== 'inactive') {
          mediaRecorderRef.current.stop();
        }
        mediaRecorderRef.current = null;
      }
      chunksRef.current = [];
      if (recordTimeoutRef.current) clearTimeout(recordTimeoutRef.current);
    };
  }, []);

  // 拍照
  const handleCapture = () => {
    const video = videoRef.current;
    const canvas = document.createElement('canvas');
    // 降低canvas分辨率，减轻内存压力
    canvas.width = 640;
    canvas.height = 480;
    canvas.getContext('2d').drawImage(video, 0, 0, 640, 480);
    const img = canvas.toDataURL('image/png');
    onCapture && onCapture(img);
    onClose();
  };

  // 开始录像
  const startRecording = () => {
    chunksRef.current = [];
    const recorder = new window.MediaRecorder(streamRef.current, { mimeType: 'video/webm' });
    mediaRecorderRef.current = recorder;
    recorder.ondataavailable = e => {
      if (e.data.size > 0) chunksRef.current.push(e.data);
    };
    recorder.onstop = () => {
      const blob = new Blob(chunksRef.current, { type: 'video/webm' });
      const url = URL.createObjectURL(blob);
      onCapture && onCapture(url, 'video');
      onClose();
      chunksRef.current = [];
    };
    recorder.start();
    setIsRecording(true);
    // 最多录10秒，超时自动停止
    recordTimeoutRef.current = setTimeout(() => {
      if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
        mediaRecorderRef.current.stop();
        setIsRecording(false);
      }
    }, 10000);
  };

  // 停止录像
  const stopRecording = () => {
    if (recordTimeoutRef.current) clearTimeout(recordTimeoutRef.current);
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      setIsRecording(false);
    }
  };

  // 按钮事件
  const handlePressStart = () => {
    timerRef.current = setTimeout(() => {
      startRecording();
    }, 300); // 300ms 以内为拍照，以上为录像
  };

  const handlePressEnd = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      if (!isRecording) {
        handleCapture(); // 短按拍照
      } else {
        stopRecording(); // 长按松开，结束录像
      }
    }
  };

  return (
    <div style={{
      position: 'fixed', left: 0, top: 0, width: '100vw', height: '100vh', background: '#000', zIndex: 9999,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center'
    }}>
      {/* 关闭按钮 */}
      <div style={{ position: 'absolute', left: 24, top: 32, fontSize: 40, color: '#fff', zIndex: 2, cursor: 'pointer' }} onClick={onClose}>×</div>
      {/* 摄像头画面，渲染分辨率降为320x240，减轻渲染压力 */}
      <video ref={videoRef} width={320} height={240} style={{ width: '100vw', height: '100vh', objectFit: 'cover' }} />
      {/* 底部操作栏 */}
      <div style={{
        position: 'absolute', bottom: 120, width: '100vw', display: 'flex', flexDirection: 'column', alignItems: 'center',
        // 录制时隐藏动画/阴影（如有）
        filter: isRecording ? 'none' : undefined
      }}>
        <div style={{ color: '#fff', fontSize: 20, marginBottom: 32 }}>
          {isRecording ? '正在录像...(最多10秒)' : '轻触拍照，长按摄像'}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100vw' }}>
          {/* 禁用闪光灯按钮 */}
          <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
            <svg width="36" height="36" viewBox="0 0 36 36">
              <g>
                <polyline points="16,8 20,16 14,16 18,28" fill="none" stroke="#fff" strokeWidth="2"/>
                <line x1="10" y1="26" x2="26" y2="10" stroke="#fff" strokeWidth="3"/>
              </g>
            </svg>
          </div>
          {/* 拍照/录像按钮 */}
          <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
            <div
              style={{
                width: 80, height: 80, borderRadius: '50%', border: '4px solid #fff',
                background: isRecording ? '#f33' : '#fff', boxShadow: isRecording ? 'none' : '0 2px 12px #0008', cursor: 'pointer'
              }}
              onMouseDown={handlePressStart}
              onMouseUp={handlePressEnd}
              onMouseLeave={handlePressEnd}
              onTouchStart={handlePressStart}
              onTouchEnd={handlePressEnd}
            />
          </div>
          {/* 切换摄像头按钮（装饰） */}
          <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
            <svg width="36" height="36" viewBox="0 0 36 36"><path d="M18 6v4M18 26v4M6 18h4M26 18h4M10 10l4 4M26 26l-4-4" stroke="#fff" strokeWidth="2" fill="none"/><circle cx="18" cy="18" r="16" stroke="#fff" strokeWidth="2" fill="none"/></svg>
          </div>
        </div>
      </div>
    </div>
  );
} 